package com.ssy.lingxi.order.serviceimpl.mobile;

import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.order.entity.OrderDO;
import com.ssy.lingxi.order.model.constant.BuyerInnerStatusEnum;
import com.ssy.lingxi.order.model.constant.OrderOuterStatusEnum;
import com.ssy.lingxi.order.model.dto.MobileOrderPageDTO;
import com.ssy.lingxi.order.model.vo.basic.request.OrderAgreeVO;
import com.ssy.lingxi.order.model.vo.basic.request.OrderIdVO;
import com.ssy.lingxi.order.model.vo.basic.request.OrderReasonVO;
import com.ssy.lingxi.order.model.vo.basic.response.OrderPayTypeDetailVO;
import com.ssy.lingxi.order.model.vo.basic.response.PayResultDetailVO;
import com.ssy.lingxi.order.model.vo.buyer.request.BuyerOrderPayVO;
import com.ssy.lingxi.order.model.vo.buyer.request.BuyerPayResultVO;
import com.ssy.lingxi.order.model.vo.buyer.request.BuyerReceiveVO;
import com.ssy.lingxi.order.model.vo.buyer.response.BuyerPayResultDetailVO;
import com.ssy.lingxi.order.model.vo.mobile.request.MobileManagePageVO;
import com.ssy.lingxi.order.model.vo.mobile.request.MobileOrderDeliveryTimeUpdateVO;
import com.ssy.lingxi.order.model.vo.mobile.request.MobilePageVO;
import com.ssy.lingxi.order.model.vo.mobile.response.*;
import com.ssy.lingxi.order.repository.OrderRepository;
import com.ssy.lingxi.order.service.base.IBaseCacheService;
import com.ssy.lingxi.order.service.base.IBaseMobileOrderService;
import com.ssy.lingxi.order.service.mobile.IMobileBuyerOrderService;
import com.ssy.lingxi.order.service.web.IBuyerOrderService;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * App - 采购订单相关接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-09-22
 */
@Service
public class MobileBuyerOrderServiceImpl implements IMobileBuyerOrderService {
    @Resource
    private IBaseCacheService baseCacheService;

    @Resource
    private IBaseMobileOrderService baseMobileOrderService;

    @Resource
    private IBuyerOrderService buyerOrderService;

    @Resource
    private OrderRepository orderRepository;


    /**
     * APP-未发货调整订单送货时间
     * @param headers Http头部信息
     * @param updateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateDeliveryTime(HttpHeaders headers, MobileOrderDeliveryTimeUpdateVO updateVO) {
        baseCacheService.needLoginFromMobile(headers);

        OrderDO order = orderRepository.findById(updateVO.getOrderId()).orElse(null);
        if (order == null) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }
        //更新订单送货时间
        order.setDeliverPeriod(updateVO.getDeliverPeriod());

        orderRepository.save(order);
        return Wrapper.success();
    }

    /**
     * 获取订单内部、外部状态列表
     *
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<MobilePageItemVO> getPageItems(HttpHeaders headers) {
        baseCacheService.needLoginFromMobile(headers);
        MobilePageItemVO itemVO = new MobilePageItemVO();
        itemVO.setInnerStatus(BuyerInnerStatusEnum.toDropdownList());
        itemVO.setOuterStatus(OrderOuterStatusEnum.toDropdownList());
        return Wrapper.success(itemVO);
    }

    /**
     * 全部订单 - 分页查询订单
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileOrderManageQueryVO>> pageOrders(HttpHeaders headers, MobileManagePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileBuyerOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getKeyword(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getInnerStatus(), pageVO.getOuterStatus(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileOrderManageQueryVO queryVO = new MobileOrderManageQueryVO(order);
            queryVO.setShowAfterSales(baseMobileOrderService.canOrderAfterSale(order));
            queryVO.setShowArchive(baseMobileOrderService.canOrderArchive(order));
            queryVO.setShowBuyAgain(baseMobileOrderService.canOrderAgain(order));
            queryVO.setShowCancel(baseMobileOrderService.canOrderCancel(order));
            queryVO.setShowComment(baseMobileOrderService.canOrderComment(order));
            queryVO.setShowConfirmContract(baseMobileOrderService.canOrderConfirmContract(order));
            queryVO.setShowConfirmReception(baseMobileOrderService.canOrderConfirmReception(order));
            queryVO.setShowGradeOne(baseMobileOrderService.canOrderValidateGradeOne(order));
            queryVO.setShowGradeTwo(baseMobileOrderService.canOrderValidateGradeTwo(order));
            queryVO.setShowPay(baseMobileOrderService.canOrderPay(order));
            queryVO.setShowReceive(baseMobileOrderService.canOrderReceive(order));
            queryVO.setShowReception(baseMobileOrderService.canOrderCreateReception(order));
            queryVO.setShowSubmit(baseMobileOrderService.canOrderSubmit(order));
            queryVO.setShowModifyDeliverTime(baseMobileOrderService.canBuyerModifyDeliverTime(order));
            queryVO.setShowRefund(baseMobileOrderService.canBuyerRefundOrder(order));
            queryVO.setShowDelete(baseMobileOrderService.canBuyerDeleteOrder(order));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 订单退款
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 退款结果
     */
    @Override
    public Wrapper<Void> orderRefund(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return buyerOrderService.orderRefund(loginUser, idVO);
    }

    /**
     * 取消订单
     *
     * @param headers  Http头部信息
     * @param reasonVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> cancelOrder(HttpHeaders headers, OrderReasonVO reasonVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return buyerOrderService.cancelOrder(loginUser, reasonVO);
    }

    /**
     * 全部订单 - 分页查询订单 - 订单删除
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> pageOrderDelete(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return buyerOrderService.pageOrderDelete(loginUser, idVO);
    }

    /**
     * “待审核订单（一级）” - 分页查询订单列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileOrderQueryVO>> pageToValidateGradeOneOrders(HttpHeaders headers, MobilePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileBuyerOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getKeyword(), BuyerInnerStatusEnum.BUYER_VALIDATE_GRADE_ONE.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(MobileOrderQueryVO::new).collect(Collectors.toList())));
    }

    /**
     * “待审核订单（一级）” - 审核
     *
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 审核结果
     */
    @Override
    public Wrapper<Void> validateOrderGradeOne(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return buyerOrderService.validateOrderGradeOne(loginUser, agreeVO);
    }

    /**
     * “待审核订单（二级）” - 分页查询订单列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileOrderQueryVO>> pageToValidateGradeTwoOrders(HttpHeaders headers, MobilePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileBuyerOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getKeyword(), BuyerInnerStatusEnum.BUYER_VALIDATE_GRADE_TWO.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(MobileOrderQueryVO::new).collect(Collectors.toList())));
    }

    /**
     * “待审核订单（二级）” - 审核
     *
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 审核结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> validateOrderGradeTwo(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return buyerOrderService.validateOrderGradeTwo(loginUser, agreeVO);
    }

    /**
     * “待提交订单” - 分页查询订单列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileToSubmitOrderQueryVO>> pageToSubmitOrders(HttpHeaders headers, MobilePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileBuyerOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getKeyword(), BuyerInnerStatusEnum.BUYER_TO_SUBMIT.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileToSubmitOrderQueryVO queryVO = new MobileToSubmitOrderQueryVO(order);
            queryVO.setShowCancel(baseMobileOrderService.canOrderCancel(order));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待提交订单” - 提交
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 审核结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> submitValidateOrder(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return buyerOrderService.submitValidateOrder(loginUser, idVO);
    }

    /**
     * “待支付订单” - 分页查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileOrderQueryVO>> pageToPayOrders(HttpHeaders headers, MobilePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileToPayOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getKeyword(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileOrderManageQueryVO queryVO = new MobileOrderManageQueryVO(order);
            queryVO.setShowCancel(baseMobileOrderService.canOrderCancel(order));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待支付订单” - 查询支付方式与支付渠道列表
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<MobilePayTypeDetailVO>> getToPayOrderPayTypes(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Wrapper<List<OrderPayTypeDetailVO>> payTypeResult = buyerOrderService.getToPayOrderPayTypes(loginUser, idVO);
        if(payTypeResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(payTypeResult.getCode(), payTypeResult.getMessage());
        }

        return Wrapper.success(payTypeResult.getData().stream().flatMap(payType -> payType.getPayChannels().stream().map(payChannel -> new MobilePayTypeDetailVO(payType.getFundMode(), payType.getPayType(), payType.getPayTypeName(), payChannel.getPayChannel(), payChannel.getPayChannelName()))).sorted(Comparator.comparingInt(MobilePayTypeDetailVO::getPayType).thenComparingInt(MobilePayTypeDetailVO::getPayChannel)).collect(Collectors.toList()));
    }

    /**
     * “待支付订单” - 订单支付
     *
     * @param headers HttpHeader信息
     * @param payVO   接口参数
     * @return 支付链接（在线支付）
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<PayResultDetailVO> orderPay(HttpHeaders headers, BuyerOrderPayVO payVO) {
        return buyerOrderService.orderPay(headers, payVO);
    }

    /**
     * “待支付订单” - 查询支付结果
     *
     * @param headers  HttpHeader信息
     * @param resultVO 接口参数
     * @return 支付结果
     */
    @Override
    public Wrapper<BuyerPayResultDetailVO> findPayResult(HttpHeaders headers, BuyerPayResultVO resultVO) {
        return buyerOrderService.findPayResult(headers, resultVO);
    }

    /**
     * “待发货订单” - 查询订单列表
     *
     * @param headers HttpHeader信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileToDeliveryOrderQueryVO>> pageToDeliveryOrders(HttpHeaders headers, MobilePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileBuyerOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getKeyword(),  null, OrderOuterStatusEnum.TO_CONFIRM_DELIVERY.getCode(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order->{
            MobileToDeliveryOrderQueryVO queryVO = new MobileToDeliveryOrderQueryVO(order);
            queryVO.setShowAfterSales(baseMobileOrderService.canOrderAfterSale(order));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待确认收货订单” -查询订单列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileOrderQueryVO>> pageToReceiveOrders(HttpHeaders headers, MobilePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileBuyerOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getKeyword(), BuyerInnerStatusEnum.BUYER_TO_RECEIVE.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(MobileOrderQueryVO::new).collect(Collectors.toList())));
    }

    /**
     * “待确认收货订单” - 确认收货
     *
     * @param headers   Http头部信息
     * @param receiveVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> receiveOrder(HttpHeaders headers, BuyerReceiveVO receiveVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return buyerOrderService.receiveOrder(loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), loginUser.getMemberRoleName(), receiveVO.getOrderId(), receiveVO.getBatchNo(), receiveVO.getReceiveBill());
    }

    /**
     * 采购订单详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileOrderDetailVO> findOrderDetail(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return baseMobileOrderService.findMobileOrderDetail(loginUser.getMemberId(), loginUser.getMemberRoleId(), idVO.getOrderId());
    }
}
